import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QMessageBox, QStackedWidget,
                             QGroupBox, QFormLayout, QDialog, QTabWidget, QTableWidget,
                             QTableWidgetItem, QHeaderView, QComboBox, QTextEdit, QGridLayout,
                             QSpinBox, QRadioButton, QButtonGroup)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database
from iteration5_user_management.create_user import UserCreator
from iteration5_user_management.query_user import UserQuery
from iteration5_user_management.update_user import UserUpdater
from iteration5_user_management.delete_user import UserDeleter
from iteration5_user_management.login import UserLogin

# 用户创建窗口
class CreateUserDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('新建用户')
        self.setGeometry(300, 300, 400, 300)
        self.creator = UserCreator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText('例如: admin')
        form_layout.addRow('用户名:', self.username_input)
        
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText('请输入密码')
        self.password_input.setEchoMode(QLineEdit.Password)
        form_layout.addRow('密码:', self.password_input)
        
        self.role_combo = QComboBox()
        self.role_combo.addItem('管理员', 'admin')
        self.role_combo.addItem('老师', 'teacher')
        self.role_combo.addItem('学生', 'student')
        form_layout.addRow('角色:', self.role_combo)
        
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText('例如: 张三')
        form_layout.addRow('姓名:', self.name_input)
        
        self.contact_input = QLineEdit()
        self.contact_input.setPlaceholderText('例如: 13800138000')
        form_layout.addRow('联系方式:', self.contact_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('用户信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.create_button = QPushButton('创建')
        self.create_button.clicked.connect(self.create_user)
        button_layout.addWidget(self.create_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def create_user(self):
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()
        role = self.role_combo.currentData()
        name = self.name_input.text().strip() or None
        contact = self.contact_input.text().strip() or None
        
        if not username or not password:
            QMessageBox.warning(self, '警告', '用户名和密码不能为空')
            return
        
        result = self.creator.create_user(username, password, role, name, contact)
        
        if result:
            QMessageBox.information(self, '成功', f'用户 {username} 创建成功')
            self.accept()

# 批量创建用户窗口
class BatchCreateUserDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('批量新建用户')
        self.setGeometry(300, 300, 500, 400)
        self.creator = UserCreator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 说明标签
        instruction_label = QLabel('每行输入一个用户信息，格式：用户名,密码,角色,姓名(可选),联系方式(可选)')
        instruction_label.setWordWrap(True)
        layout.addWidget(instruction_label)
        
        # 文本输入区域
        self.text_input = QTextEdit()
        self.text_input.setPlaceholderText('例如:\nadmin2,admin123,admin,管理员2\nteacher2,teacher123,teacher,教师2,13900000000\nstudent2,student123,student,学生2')
        layout.addWidget(self.text_input)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.create_button = QPushButton('批量创建')
        self.create_button.clicked.connect(self.batch_create_users)
        button_layout.addWidget(self.create_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def batch_create_users(self):
        text = self.text_input.toPlainText().strip()
        if not text:
            QMessageBox.warning(self, '警告', '请输入用户信息')
            return
        
        lines = text.split('\n')
        users_data = []
        
        for line in lines:
            parts = [part.strip() for part in line.split(',')]
            if len(parts) < 3:
                QMessageBox.warning(self, '警告', f'格式错误: {line}\n请确保至少包含用户名、密码和角色')
                return
            
            username = parts[0]
            password = parts[1]
            role = parts[2]
            name = parts[3] if len(parts) > 3 else None
            contact = parts[4] if len(parts) > 4 else None
            
            users_data.append((username, password, role, name, contact))
        
        if users_data:
            success_count, total_count = self.creator.batch_create_users(users_data)
            QMessageBox.information(self, '成功', f'批量创建完成：成功 {success_count}/{total_count}')
            self.accept()

# 根据班级批量创建学生用户窗口
class BatchCreateStudentUsersByClassDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('根据班级批量创建学生用户')
        self.setGeometry(300, 300, 400, 200)
        self.creator = UserCreator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 说明标签
        instruction_label = QLabel('将为指定班级的所有学生创建用户账号，用户名和密码均为学号')
        instruction_label.setWordWrap(True)
        layout.addWidget(instruction_label)
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 获取所有班级信息
        db = Database()
        db.connect()
        db.cursor.execute(
            "SELECT DISTINCT class_name FROM student ORDER BY class_name"
        )
        classes = db.cursor.fetchall()
        db.close()
        
        # 班级选择下拉框
        self.class_combo = QComboBox()
        for class_name in classes:
            self.class_combo.addItem(class_name[0])
        form_layout.addRow('班级:', self.class_combo)
        
        # 添加表单到主布局
        form_group = QGroupBox('班级信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.create_button = QPushButton('批量创建')
        self.create_button.clicked.connect(self.batch_create_student_users)
        button_layout.addWidget(self.create_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def batch_create_student_users(self):
        class_name = self.class_combo.currentText()
        
        if not class_name:
            QMessageBox.warning(self, '警告', '请选择班级')
            return
        
        success_count, total_count = self.creator.batch_create_student_users_by_class(class_name)
        
        if total_count == 0:
            QMessageBox.warning(self, '警告', f'班级 {class_name} 没有学生信息')
        else:
            QMessageBox.information(self, '成功', f'批量创建完成：成功 {success_count}/{total_count}')
            self.accept()

# 用户查询窗口
class QueryUserWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.query = UserQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询选项
        option_group = QGroupBox('查询选项')
        option_layout = QVBoxLayout()
        
        self.query_all_btn = QRadioButton('查询所有用户')
        self.query_all_btn.setChecked(True)
        option_layout.addWidget(self.query_all_btn)
        
        self.query_by_username_btn = QRadioButton('根据用户名查询用户')
        option_layout.addWidget(self.query_by_username_btn)
        
        self.query_by_role_btn = QRadioButton('根据角色查询用户')
        option_layout.addWidget(self.query_by_role_btn)
        
        # 创建按钮组
        self.query_button_group = QButtonGroup()
        self.query_button_group.addButton(self.query_all_btn, 1)
        self.query_button_group.addButton(self.query_by_username_btn, 2)
        self.query_button_group.addButton(self.query_by_role_btn, 3)
        
        option_group.setLayout(option_layout)
        layout.addWidget(option_group)
        
        # 查询参数表单
        self.param_group = QGroupBox('查询参数')
        self.param_layout = QFormLayout()
        
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText('例如: admin')
        self.param_layout.addRow('用户名:', self.username_input)
        
        self.role_combo = QComboBox()
        self.role_combo.addItem('管理员', 'admin')
        self.role_combo.addItem('经理', 'manager')
        self.role_combo.addItem('普通员工', 'staff')
        self.param_layout.addRow('角色:', self.role_combo)
        
        self.param_group.setLayout(self.param_layout)
        self.param_group.setVisible(False)
        layout.addWidget(self.param_group)
        
        # 查询按钮
        self.query_btn = QPushButton('查询')
        self.query_btn.clicked.connect(self.perform_query)
        layout.addWidget(self.query_btn)
        
        # 结果表格
        self.result_table = QTableWidget()
        self.result_table.setColumnCount(6)
        self.result_table.setHorizontalHeaderLabels(['用户ID', '用户名', '角色', '姓名', '联系方式', '状态'])
        self.result_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.result_table)
        
        # 连接信号
        self.query_button_group.buttonClicked.connect(self.on_query_option_changed)
        
        self.setLayout(layout)
    
    def on_query_option_changed(self, button):
        # 隐藏所有输入框
        for i in range(self.param_layout.rowCount()):
            self.param_layout.itemAt(i * 2 + 1).widget().setVisible(False)
            self.param_layout.itemAt(i * 2).widget().setVisible(False)
        
        # 根据选择的查询方式显示相应的输入框
        if button == self.query_by_username_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(0).widget().setVisible(True)  # 用户名标签
            self.param_layout.itemAt(1).widget().setVisible(True)  # 用户名输入框
        elif button == self.query_by_role_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(2).widget().setVisible(True)  # 角色标签
            self.param_layout.itemAt(3).widget().setVisible(True)  # 角色下拉框
        else:
            self.param_group.setVisible(False)
    
    def perform_query(self):
        selected_option = self.query_button_group.checkedId()
        
        if selected_option == 1:  # 查询所有用户
            users = self.query.query_all_users()
            self.display_results(users)
        
        elif selected_option == 2:  # 根据用户名查询用户
            username = self.username_input.text().strip()
            
            if not username:
                QMessageBox.warning(self, '警告', '用户名不能为空')
                return
            
            user = self.query.query_user_by_username(username)
            
            if user:
                self.display_results([user])
            else:
                self.result_table.setRowCount(0)
                QMessageBox.information(self, '提示', f'没有找到用户名为 {username} 的用户')
        
        elif selected_option == 3:  # 根据角色查询用户
            role = self.role_combo.currentData()
            users = self.query.query_users_by_role(role)
            
            if users:
                self.display_results(users)
            else:
                self.result_table.setRowCount(0)
                role_display = self.role_combo.currentText()
                QMessageBox.information(self, '提示', f'没有找到角色为 {role_display} 的用户')
    
    def display_results(self, users):
        if not users:
            self.result_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何用户信息')
            return
        
        self.result_table.setRowCount(len(users))
        
        for row, user in enumerate(users):
            self.result_table.setItem(row, 0, QTableWidgetItem(str(user[0])))
            self.result_table.setItem(row, 1, QTableWidgetItem(user[1]))
            self.result_table.setItem(row, 2, QTableWidgetItem(user[2]))
            self.result_table.setItem(row, 3, QTableWidgetItem(user[3] or '-'))
            self.result_table.setItem(row, 4, QTableWidgetItem(user[4] or '-'))
            self.result_table.setItem(row, 5, QTableWidgetItem(user[5]))

# 用户更新窗口
class UpdateUserWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.updater = UserUpdater()
        self.query = UserQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询所有用户
        self.refresh_btn = QPushButton('刷新用户列表')
        self.refresh_btn.clicked.connect(self.refresh_user_list)
        layout.addWidget(self.refresh_btn)
        
        # 用户列表
        self.user_table = QTableWidget()
        self.user_table.setColumnCount(6)
        self.user_table.setHorizontalHeaderLabels(['用户ID', '用户名', '角色', '姓名', '联系方式', '状态'])
        self.user_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.user_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.user_table.itemSelectionChanged.connect(self.on_selection_changed)
        layout.addWidget(self.user_table)
        
        # 更新表单
        self.update_group = QGroupBox('更新用户信息')
        update_layout = QFormLayout()
        
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText('留空表示不修改密码')
        self.password_input.setEchoMode(QLineEdit.Password)
        update_layout.addRow('新密码:', self.password_input)
        
        self.role_combo = QComboBox()
        self.role_combo.addItem('管理员', 'admin')
        self.role_combo.addItem('老师', 'teacher')
        self.role_combo.addItem('学生', 'student')
        update_layout.addRow('新角色:', self.role_combo)
        
        self.name_input = QLineEdit()
        update_layout.addRow('新姓名:', self.name_input)
        
        self.contact_input = QLineEdit()
        update_layout.addRow('新联系方式:', self.contact_input)
        
        self.update_group.setLayout(update_layout)
        layout.addWidget(self.update_group)
        
        # 更新按钮
        self.update_btn = QPushButton('更新用户信息')
        self.update_btn.clicked.connect(self.update_user)
        self.update_btn.setEnabled(False)
        layout.addWidget(self.update_btn)
        
        self.setLayout(layout)
        
        # 初始加载用户列表
        self.refresh_user_list()
    
    def refresh_user_list(self):
        users = self.query.query_all_users()
        
        if not users:
            self.user_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何用户信息')
            return
        
        self.user_table.setRowCount(len(users))
        
        for row, user in enumerate(users):
            self.user_table.setItem(row, 0, QTableWidgetItem(str(user[0])))
            self.user_table.setItem(row, 1, QTableWidgetItem(user[1]))
            self.user_table.setItem(row, 2, QTableWidgetItem(user[2]))
            self.user_table.setItem(row, 3, QTableWidgetItem(user[3] or '-'))
            self.user_table.setItem(row, 4, QTableWidgetItem(user[4] or '-'))
            self.user_table.setItem(row, 5, QTableWidgetItem(user[5]))
    
    def on_selection_changed(self):
        selected_rows = self.user_table.selectionModel().selectedRows()
        self.update_btn.setEnabled(len(selected_rows) > 0)
        
        if len(selected_rows) > 0:
            row = selected_rows[0].row()
            self.name_input.setText(self.user_table.item(row, 3).text() if self.user_table.item(row, 3).text() != '-' else '')
            self.contact_input.setText(self.user_table.item(row, 4).text() if self.user_table.item(row, 4).text() != '-' else '')
            role = self.user_table.item(row, 2).text()
            if role == 'admin':
                self.role_combo.setCurrentIndex(0)
            elif role == 'teacher':
                self.role_combo.setCurrentIndex(1)
            else:
                self.role_combo.setCurrentIndex(2)
    
    def update_user(self):
        selected_rows = self.user_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要更新的用户')
            return
        
        row = selected_rows[0].row()
        user_id = int(self.user_table.item(row, 0).text())
        username = self.user_table.item(row, 1).text()
        
        password = self.password_input.text().strip() or None
        role = self.role_combo.currentData()
        name = self.name_input.text().strip() or None
        contact = self.contact_input.text().strip() or None
        
        reply = QMessageBox.question(self, '确认更新', 
                                    f'确定要更新用户 {username} 的信息吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            result = self.updater.update_user(user_id, password, role, name, contact)
            
            if result:
                QMessageBox.information(self, '成功', f'用户 {username} 信息已更新')
                self.refresh_user_list()
                self.password_input.clear()

# 用户删除窗口
class DeleteUserWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.deleter = UserDeleter()
        self.query = UserQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询所有用户
        self.refresh_btn = QPushButton('刷新用户列表')
        self.refresh_btn.clicked.connect(self.refresh_user_list)
        layout.addWidget(self.refresh_btn)
        
        # 用户列表
        self.user_table = QTableWidget()
        self.user_table.setColumnCount(6)
        self.user_table.setHorizontalHeaderLabels(['用户ID', '用户名', '角色', '姓名', '联系方式', '状态'])
        self.user_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.user_table.setSelectionBehavior(QTableWidget.SelectRows)
        layout.addWidget(self.user_table)
        
        # 删除按钮
        self.delete_btn = QPushButton('删除选中用户')
        self.delete_btn.clicked.connect(self.delete_user)
        layout.addWidget(self.delete_btn)
        
        self.setLayout(layout)
        
        # 初始加载用户列表
        self.refresh_user_list()
    
    def refresh_user_list(self):
        users = self.query.query_all_users()
        
        if not users:
            self.user_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何用户信息')
            return
        
        self.user_table.setRowCount(len(users))
        
        for row, user in enumerate(users):
            self.user_table.setItem(row, 0, QTableWidgetItem(str(user[0])))
            self.user_table.setItem(row, 1, QTableWidgetItem(user[1]))
            self.user_table.setItem(row, 2, QTableWidgetItem(user[2]))
            self.user_table.setItem(row, 3, QTableWidgetItem(user[3] or '-'))
            self.user_table.setItem(row, 4, QTableWidgetItem(user[4] or '-'))
            self.user_table.setItem(row, 5, QTableWidgetItem(user[5]))
    
    def delete_user(self):
        selected_rows = self.user_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要删除的用户')
            return
        
        row = selected_rows[0].row()
        user_id = int(self.user_table.item(row, 0).text())
        username = self.user_table.item(row, 1).text()
        
        # 检查是否是当前登录用户
        if username == 'admin':
            QMessageBox.warning(self, '警告', '不能删除管理员账户')
            return
        
        reply = QMessageBox.question(self, '确认删除', 
                                    f'确定要删除用户 {username} 吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            result = self.deleter.delete_user(user_id)
            
            if result:
                QMessageBox.information(self, '成功', f'用户 {username} 已删除')
                self.refresh_user_list()

# 用户登录测试窗口
class LoginTestDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('用户登录测试')
        self.setGeometry(300, 300, 400, 200)
        self.login = UserLogin()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText('例如: admin')
        form_layout.addRow('用户名:', self.username_input)
        
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText('请输入密码')
        self.password_input.setEchoMode(QLineEdit.Password)
        form_layout.addRow('密码:', self.password_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('登录信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.login_button = QPushButton('登录')
        self.login_button.clicked.connect(self.test_login)
        button_layout.addWidget(self.login_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def test_login(self):
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()
        
        if not username or not password:
            QMessageBox.warning(self, '警告', '用户名和密码不能为空')
            return
        
        success, user = self.login.login(username, password)
        
        if success and user:
            QMessageBox.information(self, '成功', f'登录成功！用户: {user[1]}, 角色: {user[2]}')
            self.accept()
        else:
            QMessageBox.critical(self, '错误', '登录失败: 用户名或密码错误')

# 用户管理主窗口
class UserManagementWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('系统用户管理')
        self.setGeometry(100, 100, 800, 600)
        self.initUI()
        
    def initUI(self):
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建选项卡窗口
        tab_widget = QTabWidget()
        
        # 创建用户管理的各个功能选项卡
        self.create_tab = QWidget()
        self.query_tab = QueryUserWidget()
        self.update_tab = UpdateUserWidget()
        self.delete_tab = DeleteUserWidget()
        self.login_test_tab = QWidget()
        
        # 设置创建用户选项卡
        create_layout = QVBoxLayout()
        create_btn = QPushButton('新建用户')
        create_btn.setMinimumHeight(50)
        create_btn.setFont(QFont('Arial', 12))
        create_btn.clicked.connect(self.open_create_dialog)
        create_layout.addWidget(create_btn)
        
        # 添加批量创建用户按钮
        batch_create_btn = QPushButton('批量新建用户')
        batch_create_btn.setMinimumHeight(50)
        batch_create_btn.setFont(QFont('Arial', 12))
        batch_create_btn.clicked.connect(self.open_batch_create_dialog)
        create_layout.addWidget(batch_create_btn)
        
        # 添加根据班级批量创建学生用户按钮
        batch_create_student_btn = QPushButton('根据班级批量创建学生用户')
        batch_create_student_btn.setMinimumHeight(50)
        batch_create_student_btn.setFont(QFont('Arial', 12))
        batch_create_student_btn.clicked.connect(self.open_batch_create_student_dialog)
        create_layout.addWidget(batch_create_student_btn)
        
        create_layout.addStretch()
        self.create_tab.setLayout(create_layout)
        
        # 设置登录测试选项卡
        login_test_layout = QVBoxLayout()
        login_test_btn = QPushButton('测试用户登录')
        login_test_btn.setMinimumHeight(50)
        login_test_btn.setFont(QFont('Arial', 12))
        login_test_btn.clicked.connect(self.open_login_test_dialog)
        login_test_layout.addWidget(login_test_btn)
        login_test_layout.addStretch()
        self.login_test_tab.setLayout(login_test_layout)
        
        # 添加选项卡
        tab_widget.addTab(self.create_tab, '新建用户')
        tab_widget.addTab(self.query_tab, '查询用户')
        tab_widget.addTab(self.update_tab, '更新用户信息')
        tab_widget.addTab(self.delete_tab, '删除用户')
        tab_widget.addTab(self.login_test_tab, '用户登录测试')
        
        main_layout.addWidget(tab_widget)
        
        # 返回按钮
        back_btn = QPushButton('返回主菜单')
        back_btn.clicked.connect(self.close)
        main_layout.addWidget(back_btn)
    
    def open_create_dialog(self):
        dialog = CreateUserDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果创建成功，刷新其他选项卡的数据
            self.query_tab.perform_query()
            self.update_tab.refresh_user_list()
            self.delete_tab.refresh_user_list()
    
    def open_batch_create_dialog(self):
        dialog = BatchCreateUserDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果创建成功，刷新其他选项卡的数据
            self.query_tab.perform_query()
            self.update_tab.refresh_user_list()
            self.delete_tab.refresh_user_list()
    
    def open_batch_create_student_dialog(self):
        dialog = BatchCreateStudentUsersByClassDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果创建成功，刷新其他选项卡的数据
            self.query_tab.perform_query()
            self.update_tab.refresh_user_list()
            self.delete_tab.refresh_user_list()
    
    def open_login_test_dialog(self):
        dialog = LoginTestDialog(self)
        dialog.exec_()

# 如果直接运行此文件，提供测试界面
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = UserManagementWindow()
    window.show()
    sys.exit(app.exec_())